<template>
  <a-spin :spinning="spinning">
    <a-layout>
      <PageHeader @back="goOut" subTitle="返回"> 批量操作 </PageHeader>
      <a-layout>
        <a-layout-sider width="206" class="border-r-line ta-center border" style="border-right: none"> </a-layout-sider>
        <a-layout-content class="ph24 mb20">
          <!-- <a-col :gutter="24" style="margin-top: 20px">
            <a-alert message="工价规则、招工劳务费规则修改提交后将生成一条新的规则。" banner closable />
          </a-col> -->
          <!-- 工价规则线 -->
          <div
            v-if="empNameList && empNameList.length"
            style="font-size: 14px; font-weight: 400; color: #55565d; margin-top: 32px; display: flex"
          >
            <div style="color: #fa5051">*</div>
            {{ $route.query.isEdit ? "调薪人员" : "定薪人员" }}
            <div style="margin-left: 24px">
              <div v-if="empNameList.length < 4">
                <span style="font-size: 14px; font-weight: 500; color: #252525" v-for="(item, index) in empNameList" :key="index">
                  {{ index + 1 === empNameList.length ? item : item + "、" }}
                </span>
              </div>
              <div v-else>
                <span style="font-size: 14px; font-weight: 500; color: #252525">{{
                  empNameList[0] + "、" + empNameList[1] + "、" + empNameList[2]
                }}</span
                ><span style="font-size: 14px; font-weight: 400; color: #55565d">{{ "等" + empNameList.length + "人" }}</span>
              </div>
            </div>
          </div>
          <div class="shu">
            <div class="shuxian"></div>
            <div style="color: #000000; font-size: 16px; margin-left: 10px">{{ $route.query.isEdit ? "调薪规则" : "定薪规则" }}</div>
          </div>
          <a-radio-group v-model="size" style="margin-top: 16px" @change="radioGroupChange">
            <a-radio-button value="small"> 计时制 </a-radio-button>
            <a-radio-button value="default"> 固定薪资 </a-radio-button>
          </a-radio-group>
          <!-- 工价规则 -->
          <div v-if="size === 'default'">
            <a-form-model ref="ruleForm" style="margin-top: 25px" :model="form">
              <a-form-model-item
                ref="template"
                :label="$route.query.isEdit ? '调薪模板' : '定薪模板'"
                prop="template"
                :rules="{
                  required: true,
                  message: '必选'
                }"
              >
                <div v-if="$route.query.isFixed === 'true'">
                  <a-button class="modelBotton">
                    {{ fixedSalaryTemplateName ? fixedSalaryTemplateName : "--" }}
                  </a-button>
                </div>
                <div v-else>
                  <a-button
                    v-for="(item, index) in templateList"
                    :key="index"
                    value="horizontal"
                    class="modelBotton"
                    :class="item.style"
                    @click="templateChange(item.id, index, item)"
                  >
                    {{ item.name }}
                  </a-button>
                  <a-button type="link" class="add-field-add" @click="goIncrease()">
                    <a-icon type="plus-circle" class="add-field-icon" />新增模板
                  </a-button>
                </div>
              </a-form-model-item>
              <a-form-model-item
                ref="detailsList"
                :label="$route.query.isEdit ? '调薪明细  正式工资' : '定薪明细'"
                prop="detailsList"
                :rules="{
                  required: true,
                  message: '必填'
                }"
              >
                <a-table
                  v-if="$route.query.isFixed === 'true'"
                  :columns="columns3"
                  row-key="itemName"
                  :data-source="officialList"
                  :pagination="false"
                >
                  <template slot="amount" slot-scope="text">
                    {{ text.toFixed(2) }}
                  </template>
                  <template slot="afterAmount" slot-scope="text, record">
                    <div>
                      <a-input-number
                        v-if="record.isSum !== '1'"
                        :default-value="text"
                        :min="0"
                        :step="1"
                        :max="100000"
                        :precision="2"
                        style="margin: -5px 0; width: 120px"
                        @change="(value) => handleInputChange2(value, record.projectId)"
                      />
                      <span v-else>{{ text.toFixed(2) }}</span>
                    </div>
                  </template>
                  <template slot="amplitude" slot-scope="text, record">
                    <span :style="{ color: record.relativecolor }">{{ text }}</span>
                  </template>
                </a-table>
                <a-table v-else :columns="columns" row-key="itemName" :data-source="detailsList" :pagination="false">
                  <template v-for="col in ['trial', 'formal']" :slot="col" slot-scope="text, record">
                    <div :key="col">
                      <a-input-number
                        v-if="record.isSum !== '1'"
                        :value="text"
                        :min="0"
                        :step="1"
                        :max="100000"
                        :precision="2"
                        style="margin: -5px 0; width: 120px"
                        @change="(value) => handleInputChange(value, record.projectId, col)"
                        >{{ text }}</a-input-number
                      >
                      <span v-else>{{ text.toFixed(2) }}</span>
                    </div>
                  </template>
                </a-table>
              </a-form-model-item>
              <a-form-model-item>
                <label
                  ><span style="color: red">* </span
                  ><span style="color: rgba(0, 0, 0, 0.85)">
                    {{ $route.query.isEdit ? "调薪原因：" : "定薪原因：" }}
                  </span></label
                >
                <a-select
                  v-if="$route.query.isFixed === 'true'"
                  v-model="form.reason"
                  style="width: 300px; margin-left: 28px"
                  placeholder="请选择"
                >
                  <a-select-option :value="1"> 转正 </a-select-option>
                  <a-select-option :value="2"> 晋升 </a-select-option>
                  <a-select-option :value="3"> 调动 </a-select-option>
                  <a-select-option :value="4"> 年中调薪 </a-select-option>
                  <a-select-option :value="5"> 年度调薪 </a-select-option>
                  <a-select-option :value="6"> 特别调薪 </a-select-option>
                  <a-select-option :value="7"> 其他 </a-select-option>
                </a-select>
                <span v-else style="margin-left: 10px"> 入职定薪</span>
              </a-form-model-item>
              <a-form-model-item v-if="$route.query.isFixed === 'true'">
                <label><span style="color: red">* </span> <span style="color: rgba(0, 0, 0, 0.85)"> 调薪生效时间： </span></label>
                <a-date-picker style="width: 300px" placeholder="请选择" :disabled-date="disabledEndDate" @change="handleTimeChange" />
              </a-form-model-item>
              <a-form-model-item ref="remark" prop="remark" label="备注" :label-col="{ span: 1 }" :wrapper-col="{ span: 13 }">
                <!-- <label>备注：</label> -->
                <a-textarea v-model="form.remark" style="width: 400px" :max-length="50" />
                <a-row style="width: 405px" class="ta-right textarea-tip"> {{ form.remark ? form.remark.length : 0 }}/50字 </a-row>
              </a-form-model-item>
            </a-form-model>
            <!--  -->
            <a-modal v-model="addVisible" title="新增定薪模板" @ok="handleAddOk" @cancel="handleAddCancel">
              <a-form-model ref="addForm" :model="addForm" :rules="rules2" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-model-item label="模板名称" prop="name">
                  <a-input v-model="addForm.name" placeholder="请填写" />
                </a-form-model-item>
                <a-form-model-item label="定薪项" prop="itemIds">
                  <div class="fix-salary-item-wrapper">
                    <div v-for="(item, index) in fixItems" :key="index" :class="computeItemClass(item)" @click="handleAddSelected(item)">
                      <span>
                        {{ item.name }}
                      </span>
                    </div>
                  </div>
                </a-form-model-item>
              </a-form-model>
            </a-modal>
          </div>
          <div v-if="size === 'small' || size === 'large'">
            <div style="margin-top: 15px" class="gj">
              <span style="margin-right: 20px">工价规则</span>
              <a-select
                show-search
                option-filter-prop="children"
                :filter-option="filterOption"
                placeholder="请选择"
                allowClear
                style="width: 220px"
                v-model="salaryCalculateRuleId"
                @change="handleRulesChange"
              >
                <a-select-option v-for="(item, index) in rulusListCopy" :key="index" :value="item.id">{{ item.name }}</a-select-option>
              </a-select>
              <!-- <span class="title" @click="createDrawer">
                <a-icon class="addIcon" type="plus-circle" style="font-size: 18px; margin: 0 5px 0 25px" />新增模板
              </span> -->
            </div>
            <div style="margin-bottom: 20px">
              <div style="margin-top: 15px; font-size: 16px; font-weight: 400; color: #000000">已添加规则</div>
              <div style="margin-top: 15px">
                <a-table rowKey="id" :columns="columns2" :data-source="dataList" :pagination="paginationOpt"> </a-table>
              </div>
            </div>
          </div>
          <!-- 工价动态表单 -->
          <!-- 招工劳务费规则 -->
          <div class="shu">
            <div class="shuxian"></div>
            <div style="color: #000000; font-size: 16px; margin-left: 10px">招工劳务费规则</div>
          </div>
          <div style="margin-top: 15px" class="gj">
            <span style="margin-right: 20px">招工劳务费规则</span>
            <a-select
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              placeholder="请选择"
              allowClear
              style="width: 220px"
              v-model="redPackId"
              @change="redPackChange"
            >
              <a-select-option v-for="(item, index) in redPack" :key="index" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
            <!-- <span class="title" @click="createDrawer1">
              <a-icon class="addIcon" type="plus-circle" style="font-size: 18px; margin: 0 5px 0 25px" />新增模板
            </span> -->
          </div>
          <div style="margin-top: 15px; font-size: 16px; font-weight: 400; color: #000000">已添加规则</div>
          <div style="margin-top: 15px">
            <a-table rowKey="id" :columns="columns2" :data-source="dataList2" :pagination="paginationOpt2"> </a-table>
          </div>

          <a-divider />
          <a-row>
            <a-col class="fr">
              <a-button class="mg_r10" @click="goOut">取消</a-button>
              <a-button type="primary" @click="handleEmpyleeSubmitType">保存</a-button>
            </a-col>
          </a-row>
        </a-layout-content>
      </a-layout>
      <!-- 新增工价规则弹窗组件 -->
      <drawer ref="drawers" @update="update"></drawer>
      <drawers ref="drawersl" @fatherMethod="fatherMethod"></drawers>
    </a-layout>
  </a-spin>
</template>
<script>
import { salaryCalculateRulesListall, saveSalaryCalculateRule2, saveSalaryCalculateRuleEdit } from "@/api/staff/staff";
import { selectOutsourceSalary } from "./api";
import { salaryRulesListByPage, getSalaryCalculateRuleGroups } from "@/api/outsourcing/outrules";
import {
  selectByCompanyId,
  detaiByempId,
  empWage,
  addSalaryTemplate,
  batch,
  batchWage,
  SalaryIncrease,
  getEmpJoinDate
} from "@/api/wages/file";
import drawer from "./drawer.vue";
import drawers from "./drawers.vue";
import moment from "moment";
const columns2 = [
  {
    title: "生效时间",
    dataIndex: "timeShow",
    key: "timeShow",
    width: 100
  },
  {
    title: "基础规则",
    dataIndex: "hourAmountRuleShow",
    key: "hourAmountRuleShow1",
    width: 120
  },
  {
    title: "离职规则",
    dataIndex: "leaveOfficeRuleShow",
    key: "leaveOfficeRuleShow",
    width: 120
  }
];
const columns = [
  {
    title: "定薪项目",
    dataIndex: "itemName",
    align: "itemName",
    key: "itemName",
    scopedSlots: { customRender: "itemName" },
    width: 150
  },
  {
    title: "试用期工资",
    dataIndex: "trial",
    align: "trial",
    key: "trial",
    scopedSlots: { customRender: "trial" },
    width: 150
  },
  {
    title: "转正后工资",
    dataIndex: "formal",
    align: "formal",
    key: "formal",
    scopedSlots: { customRender: "formal" },
    width: 150
  }
];
const columns3 = [
  {
    title: "调薪项目",
    dataIndex: "itemName",
    align: "itemName",
    key: "itemName",
    scopedSlots: { customRender: "itemName" },
    width: 150
  },

  {
    title: "调薪后",
    dataIndex: "afterAmount",
    align: "afterAmount",
    key: "afterAmount",
    scopedSlots: { customRender: "afterAmount" },
    width: 150
  }
];
const fixItems = [
  {
    id: 1,
    name: "基本工资",
    selected: true,
    isDefault: true
  },
  {
    id: 2,
    name: "交通补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 3,
    name: "住房补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 4,
    name: "全勤奖",
    selected: false,
    isDefault: false
  },
  {
    id: 5,
    name: "餐补",
    selected: false,
    isDefault: false
  },
  {
    id: 6,
    name: "高温补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 7,
    name: "工龄补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 8,
    name: "夜班津贴",
    selected: false,
    isDefault: false
  },
  {
    id: 9,
    name: "通讯补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 10,
    name: "节假日补贴",
    selected: false,
    isDefault: false
  },
  {
    id: 11,
    name: "员工慰问金",
    selected: false,
    isDefault: false
  },
  {
    id: 12,
    name: "推荐奖",
    selected: false,
    isDefault: false
  },
  {
    id: 13,
    name: "职务津贴",
    selected: false,
    isDefault: false
  },
  {
    id: 14,
    name: "绩效工资",
    selected: false,
    isDefault: false
  },
  {
    id: 15,
    name: "季度奖",
    selected: false,
    isDefault: false
  },
  {
    id: 16,
    name: "销售提成",
    selected: false,
    isDefault: false
  },
  {
    id: 17,
    name: "计件工资",
    selected: false,
    isDefault: false
  },
  {
    id: 18,
    name: "工龄工资",
    selected: false,
    isDefault: false
  },
  {
    id: 19,
    name: "司龄工资",
    selected: false,
    isDefault: false
  },
  {
    id: 20,
    name: "职称工资",
    selected: false,
    isDefault: false
  },
  {
    id: 21,
    name: "技能工资",
    selected: false,
    isDefault: false
  },
  {
    id: 22,
    name: "学历工资",
    selected: false,
    isDefault: false
  }
];
export default {
  data() {
    return {
      columns,
      columns2,
      moment,
      columns3,
      dataList2: [],
      dataList: [],
      fixItems,
      fixedSalaryTemplateName: "",
      addForm: {
        name: ""
      },
      rules2: {
        name: [{ required: true, message: "必填", trigger: "blur" }]
      },
      addVisible: false,
      form: {},
      size: "small",
      showType: null,
      showType2: null,
      show: false,
      show1: false,
      spinning: true,
      templateId: "",
      salaryCalculateRuleId: undefined,
      routerData: {},
      rulusList: [],
      detailsList: [],
      officialList: [],
      ruleShow: false,
      disabledDateEnd: "",
      redPack: [],
      ruleShow1: false,
      redPackId: undefined,
      addManFormRef: {
        numList: [],
        leaveList: [],
        hourAmountDouble: null // 劳工
      },
      paginationOpt2: {
        current: 1,
        defaultCurrent: 1, // 默认当前页数
        // defaultPageSize: 5, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,

        pageSizeOptions: ["10", "20", "50", "100"],
        showTotal: (total) => `共 ${total} 条`, // 显示总数
        onShowSizeChange: (current, pageSize) => {
          this.paginationOpt2.current = 1;
          this.paginationOpt2.defaultCurrent = 1;
          this.paginationOpt2.defaultPageSize = pageSize;
          this.laowufeiguize(); // 显示列表的接口名称
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.paginationOpt2.current = current;
          this.paginationOpt2.defaultCurrent = current;
          this.paginationOpt2.defaultPageSize = size;
          this.laowufeiguize();
        }
      },
      paginationOpt: {
        current: 1,
        defaultCurrent: 1, // 默认当前页数
        // defaultPageSize: 5, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,

        pageSizeOptions: ["10", "20", "50", "100"],
        showTotal: (total) => `共 ${total} 条`, // 显示总数
        onShowSizeChange: (current, pageSize) => {
          this.paginationOpt.current = 1;
          this.paginationOpt.defaultCurrent = 1;
          this.paginationOpt.defaultPageSize = pageSize;
          this.gongjiaguize(); // 显示列表的接口名称
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.paginationOpt.current = current;
          this.paginationOpt.defaultCurrent = current;
          this.paginationOpt.defaultPageSize = size;
          this.gongjiaguize();
        }
      },
      option2: [
        // 劳工
        {
          label: "月",
          value: 1
        },
        {
          label: "天",
          value: 2
        },
        {
          label: "工时",
          value: 3
        }
      ],
      option: [
        // 劳工
        {
          label: "月",
          value: 1
        },
        {
          label: "天",
          value: 2
        },
        {
          label: "工时",
          value: 3
        }
      ],
      addManFormRef1: {
        commissionRatio1: null,
        hourAmountDouble1: null, // 劳务费
        changeList: [],
        numList1: [],
        leaveList1: [],
        specialCostDouble: undefined
      },
      rules: {
        specialCostDouble: [{ required: true, message: "请输入", trigger: "change" }]
      },
      rulusListCopy: [],
      templateList: [],
      checked3: false, // 工时抽成
      checked4: false,
      empIdList: [],
      empList: [],
      empNameList: [],
      lastId: "",
      takeDate: null,
      checked5: false,
      checked6: false,
      info: {},
      checked: false,
      checked1: false,
      labourList: [],
      companyId: this.$store.state.hr.companyId,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 }
    };
  },
  components: {
    drawer,
    drawers
  },
  created() {
    this.empList = JSON.parse(sessionStorage.getItem("empList"));
    this.getEmpJoinDate();

    this.empNameList = JSON.parse(sessionStorage.getItem("empNameList"));
    this.size = this.$route.query.isFixed === "true" ? "default" : "small";
    this.getSelectByCompanyId();
    this.salaryCalculateListall();
    if (this.$route.query.isFixed === "true") {
      this.SalaryIncreaseList();
    }

    setTimeout(() => {
      this.spinning = false;
    }, 1000);
  },
  methods: {
    SalaryIncreaseList() {
      const id = this.$route.query.templateId[0];
      SalaryIncrease(id).then((res) => {
        this.mainId = res.data.id;
        this.fixedSalaryTemplateName = res.data.fixedSalaryTemplateName;
        this.officialList = res.data.officialList;
        this.trainingList = res.data.trainingList;
        for (var i = 0; i < this.trainingList.length; i++) {
          this.trainingList[i].afterAmount = this.trainingList[i].afterAmount
            ? this.trainingList[i].afterAmount
            : this.trainingList[i].amount;
          this.trainingList[i].projectId = i;
          this.trainingList[i].amplitude = 0.0 + "%";
          this.trainingList[i].relativecolor = "#0DB6AC";
        }
        for (var p = 0; p < this.officialList.length; p++) {
          // this.officialList[p].afterAmount = this.officialList[p].afterAmount
          //   ? this.officialList[p].afterAmount
          //   : this.officialList[p].amount;
          this.officialList[p].afterAmount = 0;
          this.officialList[p].projectId = p;
          this.officialList[p].amplitude = 0.0 + "%";
          this.officialList[p].relativecolor = "#0DB6AC";
        }
      });
    },
    gongjiaguize() {
      if (this.salaryCalculateRuleId) {
        salaryRulesListByPage({
          pageNo: this.paginationOpt.defaultCurrent,
          pageSize: this.paginationOpt.defaultPageSize,
          salaryCalculateRuleGroupId: this.salaryCalculateRuleId
        }).then((res) => {
          this.dataList = res.data.entities;
          this.paginationOpt.total = res.data.entityCount;
        });
      } else {
        this.dataList = [];
      }
    },
    laowufeiguize() {
      if (this.redPackId) {
        salaryRulesListByPage({
          pageNo: this.paginationOpt2.defaultCurrent,
          pageSize: this.paginationOpt2.defaultPageSize,
          salaryCalculateRuleGroupId: this.redPackId
        }).then((res) => {
          this.dataList2 = res.data.entities;
          this.paginationOpt2.total = res.data.entityCount;
        });
      } else {
        this.dataList2 = [];
      }
    },
    handleAddCancel() {
      this.$refs.addForm.clearValidate();
    },
    handleAddOk() {
      const arr = this.fixItems.filter((item, index) => {
        if (item.selected) return true;
      });
      const data = {
        companyId: this.companyId,
        isDefault: false,
        name: this.addForm.name,
        itemIds: arr.map((item) => item.id).join(",")
      };
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          addSalaryTemplate(data)
            .then((res) => {
              this.addVisible = false;
              this.getSelectByCompanyId();
            })
            .catch((err) => {
              console.log("debug log --> ", err);
            });
        }
      });
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    computeItemClass(item) {
      if (item.id === 1) return "fix-salary-item-tag fix-salary-item-default";
      if (item.selected) return "fix-salary-item-tag fix-salary-item-selected";
      return "fix-salary-item-tag";
    },
    goIncrease() {
      this.addVisible = true;
      this.addForm = {};
      this.fixItems.forEach((item, index) => {
        if (index > 0) item.selected = false;
      });
      // this.$router.push({
      //   path: '/wages/file/template'
      // })
    },
    getDetaiByempId() {
      const id = this.templateId ? this.templateId : this.lastId;
      detaiByempId(id).then((res) => {
        this.detailsList = res.data;
        this.trialTemplateList = JSON.parse(JSON.stringify(res.data));
        this.formalTemplateList = JSON.parse(JSON.stringify(res.data));
        for (var i = 0; i < this.detailsList.length; i++) {
          this.detailsList[i].projectId = i;
          this.detailsList[i].trial = this.detailsList[i].trial ? this.detailsList[i].trial : 0;
          this.detailsList[i].formal = this.detailsList[i].formal ? this.detailsList[i].formal : 0;
        }
      });
    },
    handleAddSelected(item) {
      if (item.id === 1) return;
      item.selected = !item.selected;
    },
    getSelectByCompanyId() {
      selectByCompanyId({ companyId: this.companyId }).then((res) => {
        this.templateList = res.data;
        this.templateList.forEach((item, index) => {
          this.templateList[0].style = "buttonStyleClick";
        });
        this.templateId = this.templateList[0].id;
        this.lastId = this.templateList[0].id;
        this.lastName = this.templateList[0].name;
        // this.templateList[0].color = "#6A66F6";
        this.getDetaiByempId();
      });
    },
    templateChange(id, key, item) {
      // item.style = "buttonStyleClick";
      this.templateList[0].style = null;
      this.fixedSalaryTemplateName = item.name;
      // this.templateList[0].color = null;
      for (var i = 0; i < this.templateList.length; i++) {
        if (this.templateList[i].id === id) {
          this.templateList[i].style = "buttonStyleClick";
        } else {
          this.templateList[i].style = null;
        }
      }
      this.detailsList = [];
      this.templateId = id;
      this.detailsList;
      this.getDetaiByempId();
    },
    handleInputChange2(value, key) {
      const arr = JSON.parse(JSON.stringify(this.officialList));
      for (var i = 0; i < arr.length; i++) {
        if (i === key) {
          arr[i].afterAmount = value;
          this.officialList[i].afterAmount = value;
          if (arr[i].amount === 0) {
            arr[i].amplitude = "--";
          } else {
            arr[i].amplitude = Math.round(((arr[i].afterAmount - arr[i].amount) / arr[i].amount) * 10000) / 100 + "%";
          }
          if (arr[i].afterAmount - arr[i].amount > 0) {
            arr[i].relativecolor = "#FA5051";
          } else {
            arr[i].relativecolor = "#0DB6AC";
          }
        }
      }
      var s = 0;
      for (var t = 0; t < arr.length - 1; t++) {
        s += arr[t].afterAmount;
        arr[arr.length - 1].afterAmount = s;
        if (arr[arr.length - 1].amount === 0) {
          arr[arr.length - 1].amplitude = "--";
        } else {
          arr[arr.length - 1].amplitude =
            Math.round(((arr[arr.length - 1].afterAmount - arr[arr.length - 1].amount) / arr[arr.length - 1].amount) * 10000) / 100 + "%";
        }
        if (arr[arr.length - 1].afterAmount - arr[arr.length - 1].amount > 0) {
          arr[arr.length - 1].relativecolor = "#FA5051";
        } else {
          arr[arr.length - 1].relativecolor = "#0DB6AC";
        }
        this.officialList = JSON.parse(JSON.stringify(arr));
      }
    },
    handleSubmit() {
      const serviceFeeRuleAddDTO = {};
      this.empIdList = JSON.parse(JSON.stringify(this.empList));
      for (var i = 0; i < this.detailsList.length; i++) {
        this.trialTemplateList[i].amount = this.trialTemplateList[i].amount ? this.trialTemplateList[i].amount : 0;
        this.formalTemplateList[i].amount = this.formalTemplateList[i].amount ? this.formalTemplateList[i].amount : 0;
      }
      if (this.$route.query.isEdit) {
        if (this.$route.query.isFixed === "true") {
          if (!this.officialList[this.officialList.length - 1].amplitude && !this.trainingList[this.trainingList.length - 1].amplitude) {
            this.$notification["error"]({
              message: "error",
              description: "保存失败,至少更改一项调薪项目"
            });
          } else {
            this.trainingList.forEach((item, index) => {
              item.amount = item.afterAmount;
            });
            this.officialList.forEach((item, index) => {
              item.amount = item.afterAmount;
            });
            batchWage({
              serviceFeeRuleId: this.redPackId,
              idList: this.$route.query.templateId,
              id: 0,
              empId: "empId",
              serviceFeeRuleAddDTO: serviceFeeRuleAddDTO,
              isFixed: 0,
              companyId: this.companyId,
              // empId: this.routerData.empId,
              trainingFixedSalaryDetail: this.trainingList,
              officialFixedSalaryDetail: this.officialList,
              reason: this.form.reason,
              effectTime: this.takeDate,
              remark: this.form.remark,
              isOfficial: parseInt(this.routerData.employType),
              // id: this.mainId,
              trainingSalarySum: this.trainingList[this.trainingList.length - 1].afterAmount,
              officialSalarySum: this.officialList[this.officialList.length - 1].afterAmount
            }).then(({ success }) => {
              for (var i = 0; i < this.trainingList.length; i++) {
                this.trainingList[i].amount = this.trainingList[i].afterAmount;
              }
              for (var p = 0; p < this.officialList.length; p++) {
                this.officialList[p].amount = this.officialList[p].afterAmount;
              }
              if (success) {
                const values = {
                  // empIdList: JSON.parse(this.$route.query.selectedRowKeys),
                  companyId: this.companyId, // 租户id
                  serviceFeeRuleId: this.redPackId ? this.redPackId : null, // 劳务费id
                  empIdList: this.$route.query.templateId,
                  phone: "phone"
                };
                saveSalaryCalculateRuleEdit({ ...values, salaryType: this.size === "default" ? 1 : 2, id: "Batch" }).then((res) => {
                  this.$message.success("编辑成功");
                  if (this.$route.query.state === "outsourcing") {
                    this.$router.push({
                      path: "/staff/employee"
                    });
                  } else {
                    setTimeout(() => {
                      this.$router.push({
                        path: "/wages/file",
                        query: {
                          tabsKey: "2"
                        }
                      });
                    }, 500);
                  }
                });
                this.$router.push({
                  path: "/wages/file",
                  query: {
                    tabsKey: "1"
                  }
                });
                this.$notification["success"]({ message: "编辑成功" });
              }
            });
          }
        } else {
          batch({
            // empIdList: this.empIdList,
            idList: this.$route.query.templateId,
            // id: 0,
            empIdList: this.empIdList,
            // effectTime: moment(),
            serviceFeeRuleId: this.redPackId ? this.redPackId : null,
            fixedSalaryTemplateName: this.fixedSalaryTemplateName ? this.fixedSalaryTemplateName : this.lastName,
            isFixed: 1,
            isOfficial: parseInt(this.routerData.employType),
            companyId: this.companyId,
            fixedSalaryTemplateId: this.templateId ? this.templateId : this.lastId,
            reason: 0,
            trainingFixedSalaryDetail: JSON.stringify(this.trialTemplateList),
            officialFixedSalaryDetail: JSON.stringify(this.formalTemplateList),
            officialSalarySum: this.formalTemplateList[this.formalTemplateList.length - 1].amount
              ? this.formalTemplateList[this.formalTemplateList.length - 1].amount
              : 0,
            trainingSalarySum: this.trialTemplateList[this.trialTemplateList.length - 1].amount
              ? this.trialTemplateList[this.trialTemplateList.length - 1].amount
              : 0,
            remark: this.form.remark
          }).then(({ success }) => {
            if (success) {
              const values = {
                // empIdList: JSON.parse(this.$route.query.selectedRowKeys),
                companyId: this.companyId, // 租户id
                serviceFeeRuleId: this.redPackId ? this.redPackId : null, // 劳务费id
                empIdList: this.$route.query.templateId,
                phone: "phone"
              };
              saveSalaryCalculateRuleEdit({ ...values, salaryType: this.size === "default" ? 1 : 2, id: "Batch" }).then((res) => {
                this.$message.success("编辑成功");
                if (this.$route.query.state === "outsourcing") {
                  this.$router.push({
                    path: "/staff/employee"
                  });
                } else {
                  setTimeout(() => {
                    this.$router.push({
                      path: "/wages/file",
                      query: {
                        tabsKey: "2"
                      }
                    });
                  }, 500);
                }
              });
              this.$router.push({
                path: "/wages/file",
                query: {
                  tabsKey: "1"
                }
              });
              this.$notification["success"]({ message: "编辑成功" });
            }
          });
        }
      } else {
        batch({
          empIdList: this.empIdList,
          serviceFeeRuleId: this.redPackId ? this.redPackId : null,
          fixedSalaryTemplateName: this.fixedSalaryTemplateName ? this.fixedSalaryTemplateName : this.lastName,
          isFixed: 1,
          isOfficial: parseInt(this.routerData.employType),
          companyId: this.companyId,
          fixedSalaryTemplateId: this.templateId ? this.templateId : this.lastId,
          reason: 0,
          trainingFixedSalaryDetail: JSON.stringify(this.trialTemplateList),
          officialFixedSalaryDetail: JSON.stringify(this.formalTemplateList),
          officialSalarySum: this.formalTemplateList[this.formalTemplateList.length - 1].amount
            ? this.formalTemplateList[this.formalTemplateList.length - 1].amount
            : 0,
          trainingSalarySum: this.trialTemplateList[this.trialTemplateList.length - 1].amount
            ? this.trialTemplateList[this.trialTemplateList.length - 1].amount
            : 0,
          remark: this.form.remark
        }).then(({ success }) => {
          if (success) {
            this.$router.push({
              path: "/wages/file",
              query: {
                tabsKey: "1"
              }
            });
            this.$notification["success"]({ message: "编辑成功" });
          }
        });
      }
    },
    handleTimeChange(e) {
      this.takeDate = e;
      console.log(e);
    },
    handleInputChange(value, key, col) {
      const arr = JSON.parse(JSON.stringify(this.detailsList));
      if (col === "trial") {
        for (var i = 0; i < arr.length; i++) {
          if (i === key) {
            arr[i].trial = value;
            this.trialTemplateList[i].amount = value;
            this.trialTemplateList[i].name = this.trialTemplateList[i].itemName;
            // this.trialTemplateList[i].projectId = key
          }
        }
        var s = 0;
        for (var t = 0; t < arr.length - 1; t++) {
          s += arr[t].trial;
          arr[arr.length - 1].trial = s;
          this.trialTemplateList[this.trialTemplateList.length - 1].amount = s;
        }
      }
      if (col === "formal") {
        for (var p = 0; p < arr.length; p++) {
          if (p === key) {
            arr[p].formal = value;
            this.formalTemplateList[p].amount = value;
            this.formalTemplateList[p].name = this.formalTemplateList[p].itemName;
            // this.formalTemplateList[p].projectId = key
          }
        }
        var sum = 0;
        for (var a = 0; a < arr.length - 1; a++) {
          sum += arr[a].formal;
          arr[arr.length - 1].formal = sum;
          this.formalTemplateList[this.formalTemplateList.length - 1].amount = sum;
        }
      }

      this.detailsList = JSON.parse(JSON.stringify(arr));
    },
    radioGroupChange(e) {
      // this.salaryCalculateRuleId = undefined;
      // this.handleRulesChange(this.salaryCalculateRuleId);
      // if (this.size === "large") {
      //   var arr = [];
      //   this.rulusList.forEach((item, index) => {
      //     if (item.showType && item.showType === 1) {
      //       arr.push(item);
      //     }
      //   });
      //   this.rulusListCopy = JSON.parse(JSON.stringify(arr));
      // }
      // if (this.size === "small") {
      //   var arr2 = [];
      //   this.rulusList.forEach((item, index) => {
      //     if (item.showType && item.showType === 2) {
      //       arr2.push(item);
      //     }
      //   });
      //   this.rulusListCopy = JSON.parse(JSON.stringify(arr2));
      // }
    },
    // 获取数组里的每一个时间
    onDateChange(date, dateString, item) {
      item.time = dateString;
    },
    // 返回
    goOut() {
      setTimeout(() => {
        this.$router.push({
          path: "/wages/file",
          query: {
            tabsKey: "3"
          }
        });
      }, 500);
    },
    // 打开工价新增弹窗
    createDrawer() {
      this.$refs.drawers.onCreate();
    },
    // 打开劳务费新增弹窗
    createDrawer1() {
      this.$refs.drawersl.onCreate();
    },
    // 劳务费添加完成更新列表
    fatherMethod() {
      salaryCalculateRulesListall({ ruleType: 2 }).then((res) => {
        this.redPack = res.data;
      });
    },
    // 工价添加完成更新列表
    update() {
      this.rulusList = [];
      salaryCalculateRulesListall().then((res) => {
        if (res.data.length > 0) {
          res.data.map((item) => {
            if (item.ruleType === 1 || item.ruleType === 3) {
              this.rulusList.push(item);
            }
          });
        }
      });
    },
    limitNumber(value) {
      if (typeof value === "string") {
        return !isNaN(Number(value)) ? value.replace(/\./g, "") : 0;
      } else if (typeof value === "number") {
        return !isNaN(value) ? String(value).replace(/\./g, "") : 0;
      } else {
        return 0;
      }
    },
    handleEmpyleeSubmitType() {
      if (this.size === "small" || this.size === "large") {
        this.handleEmpyleeSubmit();
      }
      if (this.size === "default") {
        this.handleSubmit();
      }
    },
    // 保存
    handleEmpyleeSubmit(e) {
      const values = {
        empIdList: this.$route.query.templateId,
        companyId: this.companyId, // 租户id
        serviceFeeRuleId: this.redPackId, // 劳务费id
        salaryRuleId: this.salaryCalculateRuleId, // 工价id
        phone: "phone"
      };
      if (this.$route.query.isEdit) {
        saveSalaryCalculateRuleEdit({ ...values, salaryType: 2, id: "Batch" }).then((res) => {
          this.$message.success("编辑成功");
          if (this.$route.query.state === "outsourcing") {
            this.$router.push({
              path: "/staff/employee"
            });
          } else {
            setTimeout(() => {
              this.$router.push({
                path: "/wages/file",
                query: {
                  tabsKey: "2"
                }
              });
            }, 500);
          }
        });
      } else {
        saveSalaryCalculateRule2(values).then((res) => {
          this.$message.success("编辑成功");
          if (this.$route.query.state === "outsourcing") {
            this.$router.push({
              path: "/staff/employee"
            });
          } else {
            setTimeout(() => {
              this.$router.push({
                path: "/wages/file",
                query: {
                  tabsKey: "2"
                }
              });
            }, 500);
          }
        });
      }
    },
    // 工价列表下拉事件渲染数据
    handleRulesChange(e) {
      if (e) {
        this.paginationOpt.defaultCurrent = 1;
        this.paginationOpt.defaultPageSize = 10;
        salaryRulesListByPage({
          pageNo: this.paginationOpt.defaultCurrent,
          pageSize: this.paginationOpt.defaultPageSize,
          salaryCalculateRuleGroupId: e
        }).then((res) => {
          this.dataList = res.data.entities;
          this.paginationOpt.total = res.data.entityCount;
        });
      } else {
        this.dataList = [];
        this.paginationOpt.total = 0;
      }
    },
    // 劳务费规则下拉事件渲染数据
    redPackChange(e) {
      if (e) {
        this.paginationOpt2.defaultCurrent = 1;
        this.paginationOpt2.defaultPageSize = 10;
        salaryRulesListByPage({
          pageNo: this.paginationOpt2.defaultCurrent,
          pageSize: this.paginationOpt2.defaultPageSize,
          salaryCalculateRuleGroupId: e
        }).then((res) => {
          this.dataList2 = res.data.entities;
          this.paginationOpt2.total = res.data.entityCount;
        });
      } else {
        this.dataList2 = [];
        this.paginationOpt2.total = 0;
      }
      // if (e) {
      //   this.redPackId = e;
      //   this.ruleShow1 = true;

      //   this.redPack.map(item => {
      //     if (item.id === e) {
      //       this.showType2 = item.showType;
      //       if (item.showType === 1) {
      //         this.option2 = [
      //           {
      //             label: "月",
      //             value: 1
      //           },
      //           {
      //             label: "天",
      //             value: 3
      //           }
      //         ];
      //       } else {
      //         this.option2 = [
      //           {
      //             label: "月",
      //             value: 1
      //           },
      //           {
      //             label: "天",
      //             value: 2
      //           },
      //           {
      //             label: "工时",
      //             value: 3
      //           }
      //         ];
      //       }
      //       this.addManFormRef1.commissionRatio1 = item.commissionRatio;
      //       this.addManFormRef1.hourAmountDouble1 = item.hourAmountDouble;
      //       this.addManFormRef1.changeList = JSON.parse(item.hourAmountRule);
      //       this.addManFormRef1.numList1 = JSON.parse(item.redPacketRule);
      //       this.addManFormRef1.leaveList1 = JSON.parse(item.leaveOfficeRule);
      //       this.addManFormRef1.specialCostDouble = item.specialCostDouble;
      //       this.addManFormRef1.changeList.map(item => {
      //         item.type = String(item.type);
      //       });
      //       this.addManFormRef1.leaveList1.map(item => {
      //         item.type = String(item.type);
      //       });
      //       if (
      //         this.addManFormRef1.changeList.length > 0 ||
      //         this.addManFormRef1.hourAmountDouble1 !== 0 ||
      //         this.addManFormRef1.commissionRatio1 > 0
      //       ) {
      //         this.checked3 = true;
      //       }
      //       if (this.addManFormRef1.numList1.length > 0) {
      //         this.checked4 = true;
      //       }
      //       if (this.addManFormRef1.leaveList1.length > 0) {
      //         this.checked5 = true;
      //       }
      //       if (this.addManFormRef1.specialCostDouble) {
      //         this.checked6 = true;
      //       }
      //     }
      //   });
      // } else {
      //   this.ruleShow1 = false;
      //   this.show1 = false;
      // }
    },
    getEmpJoinDate() {
      getEmpJoinDate({
        companyId: this.$store.state.hr.companyId,
        empIdList: this.empList
      })
        .then((res) => {
          this.disabledDateEnd = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    disabledEndDate(endValue) {
      const startValue = moment(moment(this.disabledDateEnd).format("YYYY-MM-DD"), "YYYY-MM-DD");
      if (!endValue || !startValue) {
        return false;
      }
      return startValue.valueOf() >= endValue.valueOf();
    },
    // 获取工价劳务费规则列表并首次渲染页面数据
    salaryCalculateListall() {
      getSalaryCalculateRuleGroups({
        companyId: this.$store.state.hr.companyId
      }).then((res) => {
        res.data.forEach((item, index) => {
          if (item.ruleType === 1) {
            this.rulusListCopy.push(item);
          } else if (item.ruleType === 2) {
            this.redPack.push(item);
          }
        });
      });
    },
    // 工价计算数组
    handleMenuClick1(e) {
      if (e.key === "2") {
        this.labourList.push({
          type: e.key,
          number: null,
          units: "",
          newHourAmount: null
        }); // 不满月/天/工时倒扣工资
      } else {
        this.labourList.push({
          type: e.key,
          time: null,
          newHourAmount: null
        }); // 不满月/天/工时减少全价
      }
    },
    // 工价一次性红包添加事件
    onChange(e) {
      if (e.target.checked) {
        this.addManFormRef.numList.push({
          number: null,
          units: "",
          redPacketAmount: null
        });
        this.checked = true;
      } else {
        this.addManFormRef.numList = [];
        this.checked = false;
      }
    },
    // 工价一次性红包删除
    deleteNumList(item, index) {
      this.addManFormRef.numList.splice(index, 1);
      if (this.addManFormRef.numList.length === 0) {
        this.checked = false;
      }
    },
    // 工价一次性红包数组
    createNumList() {
      this.addManFormRef.numList.push({
        number: null,
        units: "",
        redPacketAmount: null
      });
    },
    // 工价计算删除
    deletelabourList(item, index) {
      this.labourList.splice(index, 1);
    },
    // 工价离职倒扣添加事件
    onChange1(e) {
      if (e.target.checked) {
        this.checked1 = true;
      } else {
        this.checked1 = false;
        this.addManFormRef.leaveList = [];
      }
    },
    // 工价离职倒扣删除
    deleteleaveList(item, index) {
      this.addManFormRef.leaveList.splice(index, 1);
      if (this.addManFormRef.leaveList.length === 0) {
        this.checked1 = false;
      }
    },
    // 工价倒扣数组
    handleMenuClick(e) {
      if (e.key === "1") {
        this.addManFormRef.leaveList.push({
          type: e.key,
          number: null,
          units: "",
          deductAmount: null
        }); // 不满月/天/工时倒扣工资
      } else {
        this.addManFormRef.leaveList.push({
          type: e.key,
          number: null,
          units: "",
          newHourAmount: null
        }); // 不满月/天/工时减少全价
      }
    },
    // 劳务费其他费用
    onChange6(e) {
      if (e.target.checked) {
        this.checked6 = true;
      } else {
        this.checked6 = false;
        this.addManFormRef1.specialCostDouble = 0;
      }
    },
    // 劳务费离职倒扣
    onChange5(e) {
      if (e.target.checked) {
        this.checked5 = true;
      } else {
        this.checked5 = false;
        this.addManFormRef1.leaveList1 = [];
      }
    },
    // 劳务费一次性红包添加事件
    onChange4(e) {
      if (e.target.checked) {
        this.addManFormRef1.numList1.push({
          number: null,
          units: null,
          redPacketAmount: null
        });
        this.checked4 = true;
      } else {
        this.addManFormRef1.numList1 = [];
        this.checked4 = false;
      }
    },
    // 劳务费工时抽成
    onChange3(e) {
      if (e.target.checked) {
        this.checked3 = true;
      } else {
        this.checked3 = false;
        this.addManFormRef1.changeList = [];
      }
    },
    // 劳务费工时抽成变更条件
    handleMenuClick2(e) {
      if (e.key === "1") {
        this.addManFormRef1.changeList.push({
          type: e.key,
          newHourAmount: null,
          time: null
        });
      } else {
        this.addManFormRef1.changeList.push({
          type: e.key,
          number: null,
          units: "",
          newHourAmount: null
        });
      }
    },
    // 劳务费一次性红包删除
    deleteNumList1(item, index) {
      this.addManFormRef1.numList1.splice(index, 1);
      if (this.addManFormRef1.numList1.length === 0) {
        this.checked4 = false;
      }
    },
    // 劳务费一次性红包数组
    createNumList1() {
      this.addManFormRef1.numList1.push({
        number: null,
        units: "",
        redPacketAmount: null
      });
    },
    // 劳务费新增倒扣条件
    deducMenuClick(e) {
      if (e.key === "1") {
        this.addManFormRef1.leaveList1.push({
          type: e.key,
          number: null,
          units: "",
          deductAmount: null
        }); // 不满月/天/工时倒扣工资
      } else {
        this.addManFormRef1.leaveList1.push({
          type: e.key,
          number: null,
          units: "",
          newHourAmount: null
        }); // 不满月/天/工时减少全价
      }
    },
    // 劳务费删除工时抽成条件
    deleteChangeList(item, index) {
      this.addManFormRef1.changeList.splice(index, 1);
      if (this.addManFormRef1.changeList.length === 0) {
        this.checked3 = false;
      }
    },
    //  劳务费离职倒扣删除
    deleteLeave(item, index) {
      this.addManFormRef1.leaveList1.splice(index, 1);
      if (this.addManFormRef1.leaveList1.length === 0) {
        this.checked5 = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
$body-width: calc(100% - 338px);
.fix-salary-item-wrapper {
  width: 400px;
  .fix-salary-item-tag {
    cursor: pointer;
    height: 28px;
    line-height: 28px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #d7d7d7;
    display: inline-block;
    font-size: 12px;
    margin-right: 10px;
    padding: 0 5px;
  }
  .fix-salary-item-default {
    background: #ededed;
    border-color: #a2a2a2;
  }
  .fix-salary-item-selected {
    background: #ffffff;
    border: 1px solid var(--primary);
    color: var(--primary);
  }
}
.border-r-line {
  border: #adadad;
}
.border {
  margin-top: 20px;
  background-color: #ffffff;
  border-right: 1px solid #e5e5e5;
}
.modelBotton {
  margin-left: 15px;
}
.shu {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 20px;
  .shuxian {
    width: 3px;
    height: 20px;
    background: var(--primary);
  }
}
.rowForm {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  white-space: nowrap;
  align-items: center;
  height: 50px;
}
.deleteIcon:hover {
  color: #fa5051;
}
.addIcon {
  color: var(--primary);
}
.gj {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.title {
  display: flex;
  flex-direction: row;
  align-items: center;
  color: var(--primary);
  cursor: pointer;
}
.buttonStyleClick {
  margin-left: 15px;
  border: 1px solid var(--primary);
  color: var(--primary);
}
</style>
